#include <tchar.h>
#include <Windows.h>
#include <string>
#include <algorithm>


// memory debugging
#if defined(_DEBUG) && defined(_MSC_VER) && (_MSC_VER > 1299) && !defined(_WIN32_WCE)
	#define CRTDBG_MAP_ALLOC
	#define _CRTDBG_MAP_ALLOC
	#define DEBUG_CLIENTBLOCK new(_CLIENT_BLOCK, __FILE__, __LINE__)
	#include <stdlib.h>
	#include <crtdbg.h>
	#define new DEBUG_CLIENTBLOCK
#endif

#include <EPubParser.h>

int _tmain(int argc, _TCHAR* argv[])
{
#if defined(_DEBUG)
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif

	std::string path;
	char szPath[MAX_PATH] = "";
	GetModuleFileNameA(NULL, szPath, MAX_PATH);
	path = szPath;
	path = path.substr(0, path.find_last_of('\\'));
	path += "\\wasteland-20120108.epub";

	EPubPointer<IEPubParser> parser;
	CreateEPubParser(parser);

	EPubPointer<IEPubDocument> doc = parser->CreateDocument();
	doc->Load(path.c_str());
	//doc->Save("D:\\test.zip");

	const EPubPointer<IEPubBuffer> buffer_mime_type = doc->GetBasicFileBuffer(EPUB_BFT_MIME_TYPE);
	const EPubPointer<IEPubBuffer> buffer_container = doc->GetBasicFileBuffer(EPUB_BFT_META_INF_CONTAINER);
	const EPubPointer<IEPubBuffer> buffer_encryption = doc->GetBasicFileBuffer(EPUB_BFT_META_INF_ENCRYPTION);
	const EPubPointer<IEPubBuffer> buffer_root = doc->GetBasicFileBuffer(EPUB_BFT_ROOT);


	EPubPointer<IEPubBasicMimeType> mime_type = IEPubDocument::CreateBasicFile(EPUB_BFT_MIME_TYPE).Cast<IEPubBasicMimeType>();
	mime_type->Deserialize(buffer_mime_type);
	//mime_type->Serialize();

	EPubPointer<IEPubBasicContainer> container = IEPubDocument::CreateBasicFile(EPUB_BFT_META_INF_CONTAINER).Cast<IEPubBasicContainer>();
	container->Deserialize(buffer_container);
	//container->Serialize();

	EPubPointer<IEPubBasicEncryption> encryption = IEPubDocument::CreateBasicFile(EPUB_BFT_META_INF_ENCRYPTION).Cast<IEPubBasicEncryption>();
	encryption->Deserialize(buffer_encryption);
	//encryption->Serialize();

	EPubPointer<IEPubBasicRoot> root = IEPubDocument::CreateBasicFile(EPUB_BFT_ROOT).Cast<IEPubBasicRoot>();
	root->Deserialize(buffer_root);
	//root->Serialize();

	std::string root_href = container->GetRootFile();
	root_href = root_href.substr(0, root_href.find_last_of('/'));

	
	for(EPubPointer<IEPubPage> page = root->GetPaging()->GetFirstPage();
		page;
		page = page->GetNextPage())
	{
		EPubPointer<IEPubMedia> media = page->GetMediaFile();
		media->Deserialize(doc->GetFileBuffer((root_href + "/" + media->GetHref()).c_str()));

	}

	return 0;
}